#include <request/friendrequest.h>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <entity/result.h>
#include <QJsonArray>

Friendrequest::Friendrequest(QObject *parent)
    : QObject{parent}
{
    manager = new QNetworkAccessManager(this);
    connect(manager,&QNetworkAccessManager::finished,this,&Friendrequest::onFinished);
}

//好友信息申请接口
void Friendrequest::friendInformation(const int &id)
{
    QNetworkRequest frequest(QUrl("http://"+ip+":9000/friend/list?id=" + QString::number(id)));
    frequest.setRawHeader("Content-Type","application/json");
    manager->get(frequest);
}

//搜索好友接口
void Friendrequest::serchFriendByNickName(const int &search_id, const QString &search_name)
{
    QNetworkRequest frequest(QUrl("http://"+ip+":9000/friend/search?search_id=" + QString::number(search_id)
                                  + "&search_name=" + search_name));
    frequest.setRawHeader("Content-Type","application/json");
    manager->get(frequest);
}

//获取URI
QString Friendrequest::getUri(const QString &url)
{
    int l1 = url.length();
    int n;
    for(int i=0;i<l1;i++){
        if(url[i]=='?'){
            n = i;
            break;
        }
    }
    int l2 = url.lastIndexOf(":") + 5;
    return url.mid(l2,n - l2);
}

//好友列表请求响应接口
void Friendrequest::onFinished(QNetworkReply *reply)
{
    QString url = reply->url().toString();
    QString uri = getUri(url);
    QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
    QJsonObject obj = doc.object();
    std::vector<FriendInfo> friendList;
    QJsonArray dataArray = obj["data"].toArray();
    for (QJsonValueRef item : dataArray) {
        if (item.isObject()) {
            QJsonObject friendObj = item.toObject();
            int id = friendObj["id"].toInt();
            QString name = friendObj["name"].toString();
            QString url = friendObj["avatar_url"].toString();
            friendList.emplace_back(id, name, url);
        }
    }
    MyNamespace::Result<std::vector<FriendInfo>> ret(obj["code"].toInt(),obj["msg"].toString(),friendList);
    if(uri == "/friend/list"){
        emit(friendFinished(ret));
    }else if(uri == "/friend/search"){
        emit(serchFinished(obj));
    }
}
